package com.jalonjia.paste.dao;

import com.jalonjia.paste.pojo.Paste;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * @author jalon
 */
@Slf4j
@Component
@ConditionalOnProperty(value = "paste.datasource", havingValue = "mysql")
public class PasteDAO {
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
        String createTableSQL = "" +
                "create table if not exists paste\n" +
                "(\n" +
                "    id              varchar(6)   not null\n" +
                "        primary key,\n" +
                "    author          varchar(64)  null,\n" +
                "    description     varchar(255) null,\n" +
                "    language        varchar(32)  null,\n" +
                "    code            text         null,\n" +
                "    expiration_time timestamp    null\n" +
                ")ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;";
        jdbcTemplate.update(createTableSQL);
    }

    public void add(Paste paste) {
        String sql = "INSERT INTO paste (id, author, description, language, code, expiration_time) VALUES (?, ?, ?, ?, ?, ?)";
        jdbcTemplate.update(sql,
                paste.getId(),
                paste.getAuthor(),
                paste.getDescription(),
                paste.getLanguage(),
                paste.getCode(),
                paste.getExpirationTime()
        );
    }

    public Paste getById(String id) {
        String sql = "SELECT * FROM paste WHERE id = ?";
        List<Paste> pastes = jdbcTemplate.query(sql, rowMapper(), id);
        return pastes.size() == 0 ? null : pastes.get(0);
    }

    public Paste getByExpirationTime() {
        String sql = "SELECT * FROM paste ORDER BY expiration_time";
        List<Paste> pastes = jdbcTemplate.query(sql, rowMapper());
        return pastes.size() == 0 ? null : pastes.get(0);
    }

    public void delById(String id) {
        String sql = "DELETE FROM paste WHERE id = ?";
        jdbcTemplate.update(sql, id);
    }

    private RowMapper<Paste> rowMapper() {
        return (rs, i) -> {
            Paste p = new Paste();
            p.setId(rs.getString("id"));
            p.setAuthor(rs.getString("author"));
            p.setDescription(rs.getString("description"));
            p.setLanguage(rs.getString("language"));
            p.setCode(rs.getString("code"));
            p.setExpirationTime(rs.getTimestamp("expiration_time"));
            return p;
        };
    }
}
